from django.core.paginator import Paginator
from django.shortcuts import render, redirect
from django.http import HttpResponseForbidden, JsonResponse
import json

from meiduo.utils.response_code import RETCODE
from meiduo.utils.judgelogin import UserLoginView
from payment.models import *
from order import const


class OrderManagementView(UserLoginView):
    """订单显示视图"""
    def get(self,request,page):
        user = request.user
        orders = OrderInfo.objects.filter(user=user).order_by("-update_time")
        if not orders:
            return render(request,"user_center_order.html")

        paginator = Paginator(orders, const.page_order_number)
        # 创建分页
        total_page = paginator.num_pages
        try:
            page_orders = paginator.page(page)
        except:
            return HttpResponseForbidden("参数错误")

        for order in page_orders:
            # 遍历该用户所有历史订单
            order.sku_list = []
            order.pay_method_name = order.PAY_METHOD_CHOICES[order.pay_method-1][1]
            order.status_name = order.ORDER_STATUS_CHOICES[order.status-1][1]

            order_good_qs = OrderGoods.objects.filter(order=order)
            for order_good in order_good_qs:
                # 遍历当前订单下所有sku
                sku = order_good.sku
                sku.count = order_good.count
                sku.amount = sku.price * sku.count
                order.sku_list.append(sku)

        context = {
            "page_orders":page_orders,
            "total_page":total_page,
            "page_num":page,
        }
        return render(request,"user_center_order.html",context)


class ReviewView(UserLoginView):
    """商品评价视图"""
    def get(self,request):

        order_id = request.GET.get("order_id")
        # 校验数据
        try:
            order = OrderInfo.objects.get(order_id=order_id,user=request.user,status=OrderInfo.ORDER_STATUS_ENUM["UNCOMMENT"])
        except OrderInfo.DoesNotExist:
            return HttpResponseForbidden("参数有误")

        order_goods = order.skus.all()
        skus = []
        for order_good in order_goods:
            # 格式转换
            sku = order_good.sku
            skus.append({
                "order_id":order_id,
                "sku_id":sku.id,
                "default_image_url":sku.default_image.url,
                "name":sku.name,
                "price":str(sku.price),
                "score":order_good.score,
                "comment":order_good.comment
            })
        context = {
            "uncomment_goods_list":skus
        }
        return render(request,"goods_judge.html",context)

    def post(self,request):
        # 获取数据
        data_dict = json.loads(request.body.decode())
        order_id = data_dict.get("order_id")
        sku_id = data_dict.get("sku_id")
        comment = data_dict.get("comment")
        score = data_dict.get("score")
        is_anonymous = data_dict.get("is_anonymous")   # bool类型
        # 校验数据
        if not all([order_id,sku_id,comment,score]):
            return HttpResponseForbidden("传入参数有误")
        user = request.user
        try:
            order = OrderInfo.objects.get(order_id=order_id,user=user)
        except OrderInfo.DoesNotExist:
            return HttpResponseForbidden("传入参数有误")

        if order.status==order.ORDER_STATUS_ENUM["FINISHED"]:
            # 已评价提前响应
            return JsonResponse({"code": RETCODE.OK, "errmsg": "ok"})
        elif order.status==order.ORDER_STATUS_ENUM["UNCOMMENT"]:
            try:
                order_good = OrderGoods.objects.get(order_id=order_id,is_commented=False,sku_id=sku_id)
            except OrderGoods.DoesNotExist:
                return HttpResponseForbidden("传入参数有误")
            if len(comment) <= 5:
                return HttpResponseForbidden("传入参数有误")
            if score not in range(1,6):
                return HttpResponseForbidden("传入参数有误")
            if not isinstance(is_anonymous,bool):
                return HttpResponseForbidden("传入参数有误")

            # 业务逻辑
            order_good.comment = comment
            order_good.is_commented = True
            order_good.is_anonymous = is_anonymous
            order_good.score = score

            order.status = order.ORDER_STATUS_ENUM["FINISHED"]

            order_good.save()
            order.save()

            # 响应
            return JsonResponse({"code":RETCODE.OK,"errmsg":"ok"})
        else:
            return HttpResponseForbidden("参数有误")


